using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WinRobot
{
    public partial class WinRobot : Form
    {
        private ArrayList   lines;
        private bool        running = false;

        public WinRobot()
        {
            InitializeComponent();
            setStatusText(Color.Green, "Starting process ...");

            lines = new ArrayList();

            // Kick off robot process ... 
            robotProcess.Start();
            running = true;            

            // Handle stdio/stderr ...
            robotProcess.BeginOutputReadLine();
            robotProcess.BeginErrorReadLine();
        }

        // Handler invoked on 'Process Exit'
        private void robotProcess_Exited(object sender, EventArgs e)
        {
            setStatusText(Color.Red, "Process exited ...");
            outputRichTextBox.ForeColor = Color.Gray;
            running = false;
        }

        private void setStatusText(Color colour, String text)
        {
            statusStrip.Items[0].ForeColor = colour;
            setStatusText(text);
        }

        private void setStatusText(String text)
        {
            statusStrip.Items[0].Text = text;
            Console.WriteLine(text);
        }

        // Handler for stdout from process ...
        private void robotProcess_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
        {
            if (!String.IsNullOrEmpty(e.Data))
                {
                lines.Add(e.Data);
                outputRichTextBox.Lines = (String[])lines.ToArray(typeof(string));
                }

            setStatusText("Data received ...");
        }

        // Handler for stderr from process ...
        private void robotProcess_ErrorDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
        {
            if (!String.IsNullOrEmpty(e.Data))
                {
                lines.Add(e.Data);
                outputRichTextBox.Lines = (String[])lines.ToArray(typeof(string));
                }

            setStatusText("Error Occurred ...");
        }
            
        // Handler for main form closing ...
        private void WinRobot_FormClosing(object sender, FormClosingEventArgs e)
        {
            setStatusText("Closing app ...");

            if (running)
                robotProcess.Kill();
        }

    }
}